import React, { useState, useEffect } from 'react'
import Taro, { useRouter, useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import { View, Text, Button, Image } from '@tarojs/components'
import { AtButton, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput } from 'taro-ui'
import { request } from '@/utils'
import location from '@/assets/images/location.png'
import './index.less'

const FillingStation = () => {
  const [role, setRole] = useState('')
  const [list, setList] = useState([])
  const [price, setPrice] = useState('')
  const [oilPriceId, setOilPriceId] = useState('')
  const [oilSupplierId, setOilSupplierId] = useState('')
  const [isOpened, setIsOpened] = useState(false)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const {params} = useRouter()
  const setAppRoles = async () => {
    const userInfo = await Taro.getStorage({ key: 'userInfo'})
    const { user} = JSON.parse(userInfo.data)
    setRole(user.role)
  }
  const getList = async (index, flag) => {
    Taro.showLoading({mask: true})
    const data = await request({url: 'hkshihua/user/supplier/list', data: {pageIndex: index || page}})
    setList(flag ? [...list, ...data.list] : [...data.list])
    setTotal(data.total)
  }
  const handleClick = (item) => {
    Taro.getSetting({
      success({authSetting}) {
        if(authSetting['scope.address']) {
          Taro.openLocation({
            latitude: Number(item.lat),
            longitude: Number(item.lng),
            address: item.detailedAddress
          })
        } else {
          Taro.authorize({
            scope: 'address',
            success() {
              Taro.openLocation({
                latitude: Number(item.lat),
                longitude: Number(item.lng),
                address: item.detailedAddress
              })
            }
          })
        }
      }
    })

  }
  const handleAdd = () => {
    Taro.navigateTo({
      url: '/pages/fillingStationInfoEdit/index'
    })
  }
  const handleEdit = (item) => {
    const { name,openingHoursBegin, openingHoursEnd, id, openingFlag, lat, lng, phoneNo, detailedAddress } = item
    Taro.navigateTo({
      url: `/pages/fillingStationInfoEdit/index?name=${name}&openingHoursBegin=${openingHoursBegin}&openingHoursEnd=${openingHoursEnd}&id=${id}&selectedId=${!!openingFlag ? 1 : 0}&lat=${lat}&lng=${lng}&phoneNo=${phoneNo || ''}&detailedAddress=${detailedAddress}`
    })
  }
  const handlePriceChange = (e) => {
    setPrice(e)
  }
  const handleClose = () => {
    setIsOpened(false)
  }
  const handleSetPrice = (item) => {
    setOilSupplierId(item.id)
    setOilPriceId(item.oilPriceId)
    setIsOpened(true)
  }
  useEffect(() => {
    setAppRoles()
  }, [])

  useDidShow(() => {
    setPage(1)
    getList(1)
  })
  const handleSavePrice = async () => {
    if(!price) {
      Taro.atMessage({message: '请输入油价', type: 'error'})
      return
    }
    Taro.showLoading({mask: true})
    const { error } = await request({url: 'hkshihua/user/supplier/updatePrice', method: 'POST', header: {'content-type': 'application/json'} ,data: JSON.stringify({price, oilPriceId, oilSupplierId})})
    if(error) return
    Taro.showToast({
      title: '设置成功',
      icon: 'success',
      success() {
        setIsOpened(false)
        Taro.pageScrollTo({scrollTop: 0})
        setPage(1)
        getList(1)
      }
    })
  }
  usePullDownRefresh(() => {
    setPage(1)
    getList(1)
    Taro.stopPullDownRefresh()
  })
  useReachBottom(() => {
    setPage(page + 1)
    if(page * 10 >= total) return
    getList(page + 1, true)
  })
  return (
    <View >
        {
          list.map((item) => {
            return <View className='m-list-1' key={item.id}>
            <View className='m-item-1'>
              <View className='at-row _body _view_6p'>
                <View className='at-col at-col-1 at-col--wrap _view_6p'>
                </View>
                <View className='at-col at-col-8 at-col--wrap _view_6p' style={{fontSize: '14px'}}>

                  <View className='_view_6p'>{item.name}{role === 'ADMINISTRATOR' && params.flag &&<Text style='color:red;margin-left:10px;'>{item.price}元/升</Text>}</View>
                  <View className='_view_6p'>营业时间:{item.openingHoursBegin}-{item.openingHoursEnd}</View>
                  <View className='_view_6p'>联系电话:{item.phoneNo}</View>
                  <View className='_view_6p'><Image src={location}  style={{width: '16px', height: '16px', marginRight: '5px', verticalAlign: 'middle'}}></Image>{item.detailedAddress}</View>

                </View>
                <View className='at-col at-col-3 at-col--wrap _view_6p'>
                  {role === 'ADMINISTRATOR' && <View style={{fontSize: '14px', color: item.openingFlag ? '#333': 'red'}}>{item.openingFlag ? '正常营业' : '停止营业'}</View>}


                  <View style='margin-top:30px;'>
                    {role === 'ADMINISTRATOR' && !params.flag && <AtButton type='primary' size='small' onClick={() => {handleEdit(item)}}>编辑</AtButton>}
                    {role === 'ADMINISTRATOR' && params.flag && <AtButton type='primary' size='small' onClick={() => {handleSetPrice(item)}}>设置油价</AtButton>}
                    {['MOTORCADE', 'DRIVER'].includes(role) && <AtButton  type='primary' size='small' onClick={() => handleClick(item)}>导航</AtButton>}
                  </View>
                </View>
              </View>

            </View>

          </View>
          })
        }
        {page * 10 >= total && list.length > 0 && <View className='no-data'>暂无更多数据</View>}
        {(role !== 'ADMINISTRATOR' || params.flag) && list.length <= 0 && <View className='no-data'>暂无数据</View>}
        <View style={{height: `${role !== 'ADMINISTRATOR' ? '40px': '90px'}`}}></View>
        {
          role === 'ADMINISTRATOR' && !params.flag && (
            <View className='add-more' onClick={handleAdd}>
              +
            </View>
          )
        }
        {
          role === 'ADMINISTRATOR' && isOpened && (
            <AtModal isOpened={isOpened} onClose={handleClose}>
              <AtModalHeader>设置油价</AtModalHeader>
              <AtModalContent>
              <View>
                <AtInput cursor={-1} name='price' value={price} type='text' placeholder='请输入油价' onChange={handlePriceChange} />
                元/升
              </View>
              </AtModalContent>
              <AtModalAction><Button onClick={handleSavePrice}>确定</Button></AtModalAction>
            </AtModal>
          )
        }

      </View>
  )
}
export default FillingStation
